package com.sen.gulimall.ware.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.lang.Nullable;

import java.time.Duration;

/**
 * @author Kisen
 * @email liuqs@jaid.cn
 * @date 2022/9/23 11:55
 * @detail 自定义缓存过期时间
 */
public class CustomRedisCacheManager extends RedisCacheManager {

    public static final String SEPARATOR = "#"; //过期时间分隔符

    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /**
     * 重写父类createRedisCache方法
     * 解析表达式@Cacheable(value = "cacheName#60")，取#号后面数字，设置为过期时间，默认单位：分钟
     *
     * @param name        must not be {@literal null}.
     * @param cacheConfig can be {@literal null}.
     * @return
     */
    @Override
    protected RedisCache createRedisCache(String name, @Nullable RedisCacheConfiguration cacheConfig) {
        //名称中存在#标记，进行到期时间配置
        if (!name.isEmpty() && name.contains(SEPARATOR)) {
            String[] array = name.split(SEPARATOR);
            //配置缓存名称
            name = array[0];
            if (StringUtils.isNumeric(array[1])) {
                //配置缓存到期时间
                long ttl = Long.parseLong(array[1]);
                cacheConfig = cacheConfig.entryTtl(Duration.ofMinutes(ttl));
            }
        }
        return super.createRedisCache(name, cacheConfig);
    }

}
